package com.songtech.base.exception;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.songtech.base.common.JsonResult;


/**
 * 
 *全局异常处理
 */
@ControllerAdvice
public class BaseException {

	private Logger logger = LoggerFactory.getLogger(BaseException.class);
	
	@ExceptionHandler
	@ResponseBody
    public JsonResult exexute(HttpServletRequest request, Exception ex) {  
       
        JsonResult result = new JsonResult();
        result.status = 0;
        if(!(ex instanceof HttpSessionRequiredException))
        	logger.error(ex.getMessage(), ex);
    	
        if(ex.getMessage().contains("Expected session attribute 'user'")){
        	result.msg = "登录失效";
            return result;  
        }else if(ex instanceof BusinessException){
        	result.msg = ex.getMessage();
        	return result;
        } else if(ex instanceof Exception) {
        	result.msg = "服务系统繁忙，请稍后重试";
            return result;  
        } else if(ex.getCause() != null && ex.getCause().getMessage().contains("BusinessException")) {
        	if(ex.getCause().getMessage()!=null){
        		String message = ex.getCause().getMessage();
        		result.msg = message.substring(message.lastIndexOf(':')+1, message.length());
        	}else{
        		result.msg = "业务未知异常";
        	}
            return result;  
        } else {
        	result.msg = "业务未知异常";
            return result;  
        }
	}
}
